﻿using System;
using System.Windows.Forms;

using Moe.ECamel.Common.Entities;
using Moe.ECamel.Client.Controllers;
using Moe.ECamel.Client.WinForms.Common;

namespace Moe.ECamel.Client.WinForms.Forms
{
	public partial class SubscriptionDetailsForm : ECamelForm
	{
		private readonly EntityDetailsController<Subscription> _controller;

		public SubscriptionDetailsForm()
		{
			InitializeComponent();
		}
		public SubscriptionDetailsForm(EntityDetailsController<Subscription> controller)
			: this()
		{
			this._controller = controller;

			switch (_controller.Mode)
			{
				case DetailsMode.Create:
					this.Text = "הוספת מנוי חדש";
					break;
				case DetailsMode.Edit:
					this.Text = "עריכת פרטי מנוי";
					break;
				case DetailsMode.View:
				default:
					this.Text = "פרטי מנוי";
					break;
			}

			ApplyPermissions();
			Bind();

		}

		private void ApplyPermissions()
		{
			switch (_controller.Mode)
			{
				case DetailsMode.View:
					ConfirmationButton.Visible = false;
					CancellationButton.Text = "יציאה";
					break;
			}
			this.SubscriptionDetailsControl.DetailsMode = _controller.Mode;
		}
		private void Bind()
		{
			this.SubscriptionDetailsControl.Bind(_controller.Entity);
		}

		private void ConfirmationButton_Click(object sender, EventArgs e)
		{
			if (ApplyChanges())
			{
				this.DialogResult = DialogResult.OK;
				this.Close();
			}
		}
		private void CancellationButton_Click(object sender, EventArgs e)
		{
			this.SubscriptionDetailsControl.CancelEdit();
			this.Close();
		}

		private bool ApplyChanges()
		{
			ECamelError error = this._controller.Entity.Validate();
			if (error != null)
			{
				ECamelHelper.ShowMessage(error);
				return false;
			}
			error = this._controller.SubmitChanges();
			if (error != null)
			{
				ECamelHelper.ShowMessage(error);
				return false;
			}

			return true;
		}
	}
}